// 文件夹相关控制层
const { httpCode, dateFormat } = require("../../../util");
const {
  folderAndfileImpl,
  folderImpl,
  fileImpl
} = require("../../serviceImpl");

// 查找文件夹和文件联合表
exports.findFolderAndfile = async (req, res, next) => {
  /**
   * 如果 folderid 不存在，则表示查找一级文件夹，指的是 parentfolderid ='' 的文件夹
   * 不然就是查找 parentfolderid = folderid 的文件夹
   */
  let { userid, folderid, state } = req.body;
  let mapRes = await folderAndfileImpl.findFolderAndfileImpl(
    userid,
    folderid,
    state
  );
  let mapResMap = JSON.parse(JSON.stringify(mapRes));
  mapResMap.forEach((i) => {
    i.createtime = dateFormat(new Date(i.createtime));
    delete i.index;
  }); // 删除不必要属性
  return httpCode(res, 200, "查找成功", [...mapResMap]);
};

const isOwnerFileOrFolder = async (id, userid) => {
  let findRes = await folderAndfileImpl.findFilesOrFoldersByFileidImpl(id);
  return findRes[0].owner == userid;
};

// 放入回收站
exports.putFileOrFolderToRecycle = async (req, res, next) => {
  let { id, userid, type } = req.body;
  if (!id || !userid || !type) return httpCode(res); // 参数缺失
  if (!(await isOwnerFileOrFolder(id, userid))) return httpCode(res, 7001); // 无权限删除
  // 执行更新操作
  let stateRes;
  if (type === "excel") {
    stateRes = await fileImpl.updateFilesImpl(id, null, null, null, 2); // 设置 files 基础信息表 state 为 2
  } else {
    stateRes = await folderImpl.updateFolderImpl(id, null, 2); // 设置 Folder 基础信息表 state 为 2
  }
  if (stateRes.affectedRows === 1) return httpCode(res, 200, "已放入回收站");
  httpCode(res, 7002);
};
exports.isOwnerFileOrFolder;
